﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Transactions;
using PagedList;
using Sovigaz.DataProvider;
using Utilities;

namespace Sovigaz.Permission.Repositories
{
    public class LotRepository : GenericRepository
    {
        public LotRepository()
            : base("LotID")
        {
        }

        public ICollection<LotComplex> Lots { get; set; }

        public void Delete(int id)
        {
            var item = GetByID(id);
            if (item != null)
            {
                if (_context.Products.Count(p => p.LotID == item.LotID && !p.IsDeleted) > 0) return;
                _context.Lots.Remove(item);            
            }

            _context.SaveChanges();
        }

        public void Delete(string[] idArr)
        {
            foreach (var id in idArr)
                Delete(ConvertUtility.IntParse(id));
        }

        public int Update(Lot lot)
        {
            var updateLot = new Lot();
            
            using (var scope = new TransactionScope())
            {
                if (lot.LotID > 0)
                {
                    updateLot = GetByID(lot.LotID);
                    if (!Utility.ArrayEqual(updateLot.Tstamp, lot.Tstamp))
                        throw ExceptionHelper.CreateHttpResponseException("Dữ liệu đã bị cập nhật bởi người sử dụng khác.");
                }
                updateLot.LotID = lot.LotID;
                updateLot.LotCode = lot.LotCode;
                updateLot.Date = lot.Date;
                updateLot.Status = lot.Status;
                updateLot.Description = lot.Description;

                if (updateLot.LotID == 0)
                    _context.Lots.Add(updateLot);

                _context.SaveChanges();

                scope.Complete();
            }

            _context.Entry(updateLot).Reload();

            return updateLot.LotID;
        }

        public Lot GetByID(int id)
        {
            return _context.Lots.FirstOrDefault(p => p.LotID == id && !p.IsDeleted);
        }

        public LotRepository GetList(string whereClause, string orderBy, string orderDirection, int pageNumber)
        {
            var lots = _context.Lots.Where(whereClause)
                .Select(l=>new LotComplex()
                    {
                        LotID=l.LotID,
                        LotCode=l.LotCode,
                        Date=l.Date,
                        Status=l.Status,
                        Amount=_context.Products.Count(p=>p.LotID==l.LotID),
                        LostAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status=="M"),
                        PassAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status == "D"),
                        FailAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status == "K"),
                    })
                .OrderBy(String.Format("{0} {1}", orderBy.Trim(), orderDirection.Trim()))
                .ToPagedList(pageNumber, DefaultPageSize);

            if (lots.Count == 0 && pageNumber > 1)
            {
                pageNumber--;
                lots = _context.Lots.Where(whereClause)
                .Select(l => new LotComplex()
                {
                    LotID = l.LotID,
                    LotCode = l.LotCode,
                    Date = l.Date,
                    Status = l.Status,
                    Amount = _context.Products.Count(p => p.LotID == l.LotID),
                    LostAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status == ProductStatus.M.ToString()),
                    PassAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status == ProductStatus.D.ToString()),
                    FailAmount = _context.Products.Count(p => p.LotID == l.LotID && p.Status == ProductStatus.K.ToString()),
                })
                .OrderBy(String.Format("{0} {1}", orderBy.Trim(), orderDirection.Trim()))
                .ToPagedList(pageNumber, DefaultPageSize);
            }
            TotalItemCount = lots.TotalItemCount;
            TotalItemOnPage = lots.Count;
            PageCount = lots.PageCount;
            PageNumber = lots.PageNumber;
            Lots = lots.ToList();

            return this;
        }

        public List<Lot> GetListLot()
        {
            return _context.Lots.Where(p => !p.IsDeleted).ToList();
        }

        public int GetNextIndex()
        {
            if (_context.Lots.FirstOrDefault() == null) return 1;
            return _context.Lots.Max(p => p.LotID) + 1;
        }
    }
}
